package io.jnet.common.api.impl;

import java.nio.channels.AsynchronousSocketChannel;
import com.jfireframework.baseutil.collection.buffer.ByteBuf;
import io.jnet.common.api.ChannelContext;
import io.jnet.common.api.WriteHandler;
import io.jnet.common.bufstorage.BufStorage;
import io.jnet.common.decodec.FrameDecodec;
import io.jnet.common.streamprocessor.ProcesserUtil;
import io.jnet.common.streamprocessor.StreamProcessor;
import io.jnet.common.util.AioListener;

public class SimpleReadHandler extends AbstractReadHandler
{
    private final StreamProcessor[] processors;
    private final BufStorage        bufStorage;
    private final WriteHandler      writeHandler;
    
    public SimpleReadHandler(WriteHandler writeHandler, StreamProcessor[] processors, AsynchronousSocketChannel socketChannel, BufStorage bufStorage, FrameDecodec frameDecodec, ByteBuf<?> ioBuf, AioListener channelListener, ChannelContext serverChannelContext)
    {
        super(socketChannel, frameDecodec, ioBuf, channelListener, serverChannelContext);
        this.processors = processors;
        this.bufStorage = bufStorage;
        this.writeHandler = writeHandler;
    }
    
    protected void process(ByteBuf<?> buf) throws Throwable
    {
        Object finalResult = ProcesserUtil.process(channelContext, processors, buf, 0);
        if (finalResult instanceof ByteBuf<?>)
        {
            bufStorage.putBuf(buf);
            writeHandler.registerWrite();
        }
    }
}
